package cn.panxing.server.search;


import java.io.File;
import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.FSDirectory;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;


/**
 * 
 * @author allen
 *
 */
class TextFileSearcher {


	public static void main(String[] args) {
		TextFileSearcher textFileSearcher;
		try {
			textFileSearcher = new TextFileSearcher("/home/allen/workspace/testlucene/test/index/");
			String results[] = textFileSearcher.doSearch("java*");
			
			for(int i=0; i<results.length; ++i){
				System.out.println( results[i]);
			}
			     
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public TextFileSearcher(String indexDir) throws IOException {
		initSearch(indexDir);
	}
	
	private void initSearch(String indexDir) throws IOException {
		 //This is the directory that hosts the Lucene index
        File indexFileDir = new File(indexDir);
        if(!indexFileDir.exists()){
        	throw new IOException();
        } 
        
        FSDirectory directory = FSDirectory.getDirectory(indexFileDir,false);
        searcher = new IndexSearcher(directory);
        
        multiQuery = new QueryParser("name", new StandardAnalyzer() );       

	}


	public String[] doSearch(String queryWord) throws ParseException, IOException
	{
		
		//String queryWord = "台 + 湾";
		queryWord = queryWord.replace('[', '(');
		queryWord = queryWord.replace(']', ')');
		queryWord = queryWord.replace('-', '_');
		//queryWord = queryWord.replaceAll("/([)|(])|(-)/g"," ");
        Hits hits = searcher.search(multiQuery.parse(queryWord));
        results = new String[hits.length()]; 
        
        for(int i = 0; i < hits.length(); i++){
        	Document document = hits.doc(i);
        	results[i]=document.get("path");
        }
		return results;
	}
	
	private String results[];
	private IndexSearcher searcher;
	private QueryParser multiQuery;

}
